import plugin from '../../lib/plugins/plugin.js';
import { createRequire } from 'module';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);

export class RecommendSystem extends plugin {
    constructor() {
        super({
            name: '深度推荐系统',
            dsc: '全维度详细推荐引擎',
            event: 'message',
            priority: 6000,
            rule: [
                // 统一推荐入口
                {
                    reg: '^#?(推荐|今日推荐)(详细)?$',
                    fnc: 'generateDetailedRecommendation'
                }
            ]
        });

        this.dataPool = this.loadConfig();
    }

    loadConfig() {
        try {
            const configPath = path.join(__dirname, 'configPool.json');
            const rawData = require(configPath);
            
            // 强化数据校验
            const validate = (arr, type) => {
                if (!Array.isArray(arr)) throw new Error(`${type}必须为数组`);
                arr.forEach(item => {
                    if (!item.title && type === 'books') throw new Error('书籍必须包含title字段');
                    if (!item.title && type === 'movies') throw new Error('电影必须包含title字段');
                    if (!item.name && type === 'foods') throw new Error('美食必须包含name字段');
                });
            };

            validate(rawData.books || [], 'books');
            validate(rawData.movies || [], 'movies');
            validate(rawData.foods || [], 'foods');

            console.log('[配置加载] 数据统计:');
            console.log(`书籍：${rawData.books.length}本`);
            console.log(`电影：${rawData.movies.length}部`);
            console.log(`美食：${rawData.foods.length}种`);
            
            return rawData;
        } catch (err) {
            console.error('[配置错误]', err);
            return this.getFallbackData();
        }
    }

    async generateDetailedRecommendation() {
        const book = this._getBookDetail();
        const movie = this._getMovieDetail();
        const food = this._getFoodDetail();

        const msg = [
            "🌟 全维度深度推荐 🌟",
            "━━━━━━━━━━━━━",
            book,
            "───────────────",
            movie,
            "───────────────",
            food,
            "━━━━━━━━━━━━━",
            `📅 推荐时间：${new Date().toLocaleString()}`
        ].join('\n');

        await this.reply(msg);
        return true;
    }

    // 书籍推荐模板
    _getBookDetail() {
        const pool = this.dataPool.books;
        if (!pool.length) return '📚 书籍推荐：暂无数据';

        const totalWeight = pool.reduce((sum, b) => sum + Math.max(b.weight || 1, 1), 0);
        let random = Math.random() * totalWeight;
        
        const selected = pool.find(book => {
            random -= Math.max(book.weight || 1, 1);
            return random <= 0;
        }) || pool[0];

        return [
            '📚 书籍推荐',
            `书名：${selected.title}`,
            `作者：${selected.author || '未知作者'}`,
            `评分：${this._generateStars(selected.rating || 4)}`,
            `推荐语：${selected.quote || '暂无详细描述'}`,
            `出版年：${selected.publishYear || '未知'}`
        ].join('\n');
    }

    // 电影推荐模板
    _getMovieDetail() {
        const pool = this.dataPool.movies;
        if (!pool.length) return '🎬 电影推荐：暂无数据';

        const selected = pool[Math.floor(Math.random() * pool.length)];
        return [
            '🎬 电影推荐',
            `片名：${selected.title}`,
            `导演：${selected.director || '未知'}`,
            `主演：${selected.actors?.join(' / ') || '未知'}`,
            `类型：${selected.genre?.join(' · ') || '未分类'}`,
            `时长：${selected.duration || '未知'}分钟`,
            `评分：${this._generateStars(selected.rating || 4.5)}`
        ].join('\n');
    }

    // 美食推荐模板
    _getFoodDetail() {
        const pool = this.dataPool.foods;
        if (!pool.length) return '🍽 美食推荐：暂无数据';

        const selected = pool[Math.floor(Math.random() * pool.length)];
        return [
            '🍽 美食推荐',
            `名称：${selected.name}`,
            `类型：${selected.type || '未分类'}`,
            `主料：${selected.ingredients?.join(' · ') || '未知'}`,
            `热量：${selected.calorie ? `${selected.calorie}大卡/份` : '未知'}`,
            `推荐理由：${selected.reason || '经典美味值得尝试'}`
        ].join('\n');
    }

    // 辅助方法：生成星级
    _generateStars(rating) {
        const full = '★'.repeat(Math.floor(rating));
        const half = rating % 1 >= 0.5 ? '½' : '';
        return `${full}${half}${'☆'.repeat(5 - Math.ceil(rating))} (${rating.toFixed(1)})`;
    }

    getFallbackData() {
        return {
            books: [{
                title: "代码整洁之道",
                author: "Robert C. Martin",
                quote: "软件工艺的典范之作",
                publishYear: 2019,
                rating: 4.8,
                weight: 5
            }],
            movies: [{
                title: "肖申克的救赎",
                director: "弗兰克·德拉邦特",
                actors: ["蒂姆·罗宾斯", "摩根·弗里曼"],
                genre: ["剧情", "犯罪"],
                duration: 142,
                rating: 4.9
            }],
            foods: [{
                name: "东坡肉",
                type: "浙菜",
                ingredients: ["五花肉", "黄酒", "酱油"],
                calorie: 450,
                reason: "肥而不腻，入口即化"
            }]
        };
    }
}